var common = require("../../utils/common.js");
//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    index: -1,//第几条
    length: 10,
    total: 0,//共多少条
    adviserList: [],
    canIUse: false,
    loading: true,
    isNoerweima:false,//在线聊天不显示
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function (options) {
    var that = this;
    wx.setNavigationBarTitle({
      title: '专属顾问'
    });
    console.log("分享后进来的数据")
    console.log(options)
    if (options.xcxid) {
      that.setData({
        xcxid: options.xcxid
      })
    }

    //获取用户权限，只要不是体验版，就显示isNoerweima
    if(app.globalData.xcxtype.hasInfo=="1"){
      that.setData({
        isNoerweima:true
      })
    }
  },
  onShow: function () {
    var that = this;
    that.setData({
      loading: true
    })
    wx.login({
      success: res => {
        if (res.code) {
          var code = res.code;
          //获取xcxOpenId;
          // 获取用户信息
          wx.getSetting({
            success: res => {
              if (res.authSetting['scope.userInfo']) {
                wx.getUserInfo({
                  success: function (res) {
                    console.log(res.userInfo)
                    app.globalData.userInfo = res.userInfo;
                    app.globalData.isFind = true;
                    that.getOpenId(code);
                  }
                })
              } else {
                //未授权登录
                console.log(2);
                app.globalData.isFind = false;
                that.getOpenId(code);
                that.setData({
                  loading: false,
                  canIUse: true
                })
              }
            }
          })
        } else {
          console.log(3);
          console.log('登录失败！' + res.errMsg);
          that.setData({
            loading: true
          })
        }
      }
    })
  },

  getOpenId: function (code) {
    var that = this;
    var xcxid;
    if (that.data.xcxid) {
      console.log("1");
      xcxid = that.data.xcxid
    } else if (app.globalData.xcxshareid) {
      console.log("2");
      xcxid = app.globalData.xcxshareid
    } else {
      xcxid = app.globalData.queryWlpXcxByParams[0].id
    }
    common.ajaxPost(
      'portal/wlpUsers/getXcxOpenId.action', {
        code: code,
        xcxId: xcxid
      },
      function (res) {
        if (res && res["result"]) {
          console.log(res);
          app.globalData.xcxOpenId = res.xcxOpenId;
          // that.findUser();
          if (app.globalData.isFind) {
            //已授权
            that.findUser();
          } else {
            //未授权
          }

        }
      }
    )
  },


  openSetting: function (e) {
    console.log(e);
    var that = this;
    if (e.detail.errMsg == 'getUserInfo:fail auth deny') {
      return false;
    } else {
      console.log(e.detail.userInfo);
      app.globalData.userInfo = e.detail.userInfo;
      //授权时查询用户
      that.setData({
        canIUse: false,
        loading: true
      });
      that.findUser();
    }
  },
  detail: function (e) {
    console.log(e)
    var headimage = e.currentTarget.dataset.headimage;
    var name = e.currentTarget.dataset.name
    var id = e.currentTarget.dataset.id
    var usertype = e.currentTarget.dataset.usertype
    var hasNoReceive = e.currentTarget.dataset.hasnoreceive
    var position = e.currentTarget.dataset.position
    var weixin = e.currentTarget.dataset.weixin
    var weixinQrcode = e.currentTarget.dataset.weixinqrcode
    var phone = e.currentTarget.dataset.phone
    var address = e.currentTarget.dataset.address
    var mailbox = e.currentTarget.dataset.mailbox

    var visitingCard = e.currentTarget.dataset.visitingcard

    // app.globalData.myAdviser['headimage'] = headimage
    // app.globalData.myAdviser['name'] = name
    // app.globalData.myAdviser['id'] = id
    // app.globalData.myAdviser['usertype'] = usertype
    // app.globalData.myAdviser['hasNoReceive'] = hasNoReceive

    wx.setStorage({
      key: "adviser",
      data: this.data.adviserList[e.currentTarget.id]
    })
    wx.navigateTo({
      //url: '/pages/adviserDetail/adviserDetail'
      url: '/pages/myAdviser/myAdviser?headimage=' + headimage + '&name=' + name + '&id=' + id + '&usertype=' + usertype + '&hasNoReceive=' + hasNoReceive + '&position=' + position + '&weixin=' + weixin + '&weixinQrcode=' + weixinQrcode + '&phone=' + phone + '&address=' + address + '&mailbox=' + mailbox + '&visitingCard=' + visitingCard,
    })
  },
  getList: function () {
    var that = this;
    if (app.globalData.isGoBack) {
      //页面返回
      that.setData({
        index: -1,//第几条
        length: 10,
        total: 0,
        adviserList: []
      })
      var index = that.data.index;
      var length = that.data.length;
    } else {
      var index = that.data.index;
      var length = that.data.length;
    }

    if (index <= that.data.total) {
      index++;
      common.ajaxPost(
        'portal/wlpUsers/queryCounselorPage.action',
        {
          start: index,
          length: length,
          bid: app.globalData.bid,
          toUserId: app.globalData.userInfo.id
        },
        function (res) {
          if (res && res.length > 0) {
            var list = that.data.adviserList;
            list = list.concat(res.data);
            that.setData({
              adviserList: list,
              total: res.recordsTotal,
              index: that.data.index + res.length,
              loading: false,
              canIUse: false
            })
            if (res.recordsTotal == 0) {
              wx.showToast({
                title: '暂无数据',
                icon: 'none'
              })
            }
            that.findUserInfo();
          }
        }
      )
    } else {
      wx.showToast({
        title: '没有更多了',
        icon: 'none'
      })
    }
  },
  onReachBottom: function () {
    app.globalData.isGoBack = false;
    this.getList();
  },
  call: function (e) {
    var that = this;
    app.globalData.isGoBack = true;
    wx.makePhoneCall({
      phoneNumber: that.data.adviserList[e.currentTarget.id].phone //仅为示例，并非真实的电话号码
    })
    return false;
  },
  onShareAppMessage: function (res) {
    var xcxids;
    if (app.globalData.xcxshareid) {
      xcxids = app.globalData.xcxshareid
    } else {
      xcxids = app.globalData.queryWlpXcxByParams[0].id
    }
    return {
      title: '专属顾问',
      path: '/pages/index/index?type=adviserList&bid=' + app.globalData.bid + "&isIndex=1&xcxid=" + xcxids+"&lpid="+app.globalData.lpid,
      success: function (res) {
        // 转发成功
        console.log('/pages/index/index?type=adviserList&bid=' + app.globalData.bid + "&isIndex=1&xcxid=" + xcxids+"&lpid="+app.globalData.lpid)
        app.globalData.isGoBack = true;
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  onUnload: function () {
    app.globalData.isShareBack = true
    console.log("order退出了")
  },

  findUser: function () {
    var that = this;
    console.log(app.globalData.xcxOpenId);
    //查询用户是否存在
    common.ajaxPostNo(
      'portal/wlpUsers/queryUserInfo.action', {
        xcxOpenId: app.globalData.xcxOpenId,
        bid: app.globalData.bid,
        userType: 2
      },
      function (res) {
        if (res.data.resultCode == "1000") {
          app.globalData.userInfo = res.data.userInfo;
          that.getList();
        } else {
          //用户不存在
          that.modifyUser();
        }
        return false;
      }
    )
  },



  findUserInfo: function () {
    var that = this;
    console.log(app.globalData.xcxOpenId);
    //查询用户是否存在
    common.ajaxPostNo(
      'portal/wlpUsers/queryUserInfo.action', {
        xcxOpenId: app.globalData.xcxOpenId,
        bid: app.globalData.bid,
        userType: 2
      },
      function (res) {
        if (res.data.resultCode == "1000") {
          console.log(res);
          console.log(app);
          app.globalData.userInfo = res.data.userInfo
        }
        return false;
      }
    )
  },

  gotoAuthentication() {
    this.queryHasAuth();
    // wx.navigateTo({
    //   url: '../tmList/tmList',
    // })
    //到专属顾问认证

  },

  queryHasAuth: function () {
    //查询是否认证过了，认证过了跳转tmlist,否则认证
    var that = this;
    common.ajaxPost(
      'portal/wlpUsers/queryHasAuth.action', {
        xcxOpenId: app.globalData.xcxOpenId,
        bid: app.globalData.bid
      },
      function (res) {
        if (res && res["result"]) {
          if (res.resultMsg == "未认证!") {
            app.globalData.isAuto = false;
            wx.navigateTo({
              url: '../authentication/authentication',
            })
          } else {
            //存储顾问信息
            console.log(res);
            var GwHeadImage = res.GwHeadImage;
            var GwName = res.GwName;
            var GwUserType = res.GwUserType;
            var Gwid = res.Gwid;
            var bid = app.globalData.bid;
            wx.navigateTo({
              url: '../tmList/tmList?GwHeadImage=' + GwHeadImage + "&GwName=" + GwName + "&GwUserType=" + GwUserType + "&Gwid=" + Gwid + '&bid=' + bid,
            })
          }
        }
      }
    )
  },

  modifyUser: function () {
    //保存用户信息
    var that = this;
    common.ajaxPost(
      'portal/wlpUsers/modifyUser.action', {
        userType: 2,
        headImage: app.globalData.userInfo.avatarUrl,
        name: app.globalData.userInfo.nickName,
        bid: app.globalData.bid,
        xcxOpenId: app.globalData.xcxOpenId,
      },
      function (res) {
        console.log(res);
        if (res && res["result"]) {
          if (res.resultMsg == '操作成功') {
            //添加成功，显示列表页
            that.setData({
              canIUse: false,
              loading: false
            });
            that.getList();
          } else {
            //添加成功，显示列表页
            that.setData({
              canIUse: false,
              loading: true
            });
          }
        }
      }
    )
  },

  calls: function (e) {
    var headimage = e.currentTarget.dataset.headimage;
    var name = e.currentTarget.dataset.name
    var id = e.currentTarget.dataset.id
    var usertype = e.currentTarget.dataset.usertype

    console.log(headimage)
    wx.navigateTo({
      url: '../rooms/rooms?headimage=' + headimage + '&name=' + name + '&id=' + id + '&usertype=' + usertype,
    })

  }
})
